package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMappe;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMappe userMappe;
    @Autowired
    private WorkspaceService workspaceService;
    @Override
    public TurnoverReportVO turnover(LocalDate begin, LocalDate end) {
        List<LocalDate>localDateList=new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            localDateList.add(begin);

        }
        List<Double> turnoveramount=new ArrayList<>();
        for (LocalDate localDate : localDateList) {
            LocalDateTime begintime=LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endtime=LocalDateTime.of(localDate, LocalTime.MAX);
            Map map=new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begintime",begintime);
            map.put("endtime",endtime);
            Double sumamount=orderMapper.turnover(map);
            sumamount=sumamount==null ? 0.0 :sumamount;
            turnoveramount.add(sumamount);
        }


        return  TurnoverReportVO.builder().dateList(StringUtil.join(",", localDateList).replace("[","").replace("]",""))
                .turnoverList(StringUtil.join(",",turnoveramount).replace("[","").replace("]","")).build();
    }

    @Override
    public UserReportVO userreport(LocalDate begin, LocalDate end) {
        List<LocalDate>localDateList=new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            localDateList.add(begin);

        }
        //新增用户
        List<Long> newusernumber=new ArrayList<>();

        for (LocalDate localDate : localDateList) {
            LocalDateTime begintime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map=new HashMap();
            map.put("begintime",begintime);
            map.put("endtime",endtime);
            newusernumber.add(userMappe.countnewuser(map));

        }
        //总用户数量
        List<Long> totaluser=new ArrayList<>();

        for (LocalDate localDate : localDateList) {

            LocalDateTime endtime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map=new HashMap();

            map.put("endtime",endtime);
            totaluser.add(userMappe.countnewuser(map));

        }
        return UserReportVO.builder().dateList(StringUtil.join(",",localDateList).replace("[","").replace("]",""))
                .newUserList(StringUtil.join(",",newusernumber).replace("[","").replace("]",""))
                .totalUserList(StringUtil.join(",",totaluser).replace("[","").replace("]",""))
                .build();
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //总记录
        LocalDateTime totalbegin = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime totalend = LocalDateTime.of(end, LocalTime.MAX);
        Integer totalstatus=Orders.COMPLETED;
        Map map=new HashMap();
        map.put("totalbegin",totalbegin);
        map.put("totalend",totalend);
//        map.put("totalstatus",totalstatus);
        Integer totalorder= orderMapper.gettotalorder(map);
        //有效订单数
        Map validmap=new HashMap();
        validmap.put("totalbegin",totalbegin);
        validmap.put("totalend",totalend);
        validmap.put("totalstatus",totalstatus);
        Integer validOrderCount=orderMapper.gettotalorder(validmap);
        //订单完成率
        Double orderCompletionRate =0.0;
        if(totalorder!=0){
            orderCompletionRate= validOrderCount.doubleValue()/totalorder;
        }

        List<LocalDate>localDateList=new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            localDateList.add(begin);
        }
        //每日订单
        List<Integer> orderCountList =new ArrayList<>();
        for (LocalDate localDate : localDateList) {
            LocalDateTime begintime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map daymap=new HashMap();
            daymap.put("beginTime",begintime);
            daymap.put("endTime",endtime);
            orderCountList.add(orderMapper.orderCountList(daymap));
        }
 //每日有效订单
        List<Integer> validOrderCountList =new ArrayList<>();
        for (LocalDate localDate : localDateList) {
            LocalDateTime begintime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map validdaymap=new HashMap();
            validdaymap.put("beginTime",begintime);
            validdaymap.put("endTime",endtime);
            validdaymap.put("status",totalstatus);
            validOrderCountList.add(orderMapper.orderCountList(validdaymap));
        }
        return OrderReportVO.builder()
                .dateList(StringUtil.join(",",localDateList).replace("[","").replace("]",""))
                .totalOrderCount(totalorder)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtil.join(",",orderCountList).replace("[","").replace("]",""))
                .validOrderCountList(StringUtil.join(",",validOrderCountList).replace("[","").replace("]",""))
                .build();
    }

    @Override
    public SalesTop10ReportVO top(LocalDate begin, LocalDate end) {

         List<GoodsSalesDTO>goodsSalesDTOS=orderMapper.gettop(LocalDateTime.of(begin,LocalTime.MIN),LocalDateTime.of(end,LocalTime.MAX));
         List<String> name= goodsSalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
         List<Integer> number=goodsSalesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtil.join(",",name).replace("[","").replace("]",""))
                .numberList(StringUtil.join(",",number).replace("[","").replace("]",""))
                .build();
    }
    /**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1. 查询数据库，获取营业数据---查询最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public Double deliveryfee(LocalDate begin, LocalDate end,String courierid) {
        List<LocalDate>localDateList=new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            localDateList.add(begin);

        }
        List<Double> deliveryfee=new ArrayList<>();
        for (LocalDate localDate : localDateList) {
            LocalDateTime begintime=LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endtime=LocalDateTime.of(localDate, LocalTime.MAX);
            Map map=new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begintime",begintime);
            map.put("endtime",endtime);
            map.put("courierid",courierid);
            Double fee=orderMapper.totalfee(map);
            fee=fee==null ? 0.0 :fee;
            deliveryfee.add(fee);
        }
        double totalFee = deliveryfee.stream().mapToDouble(Double::doubleValue).sum();
        return totalFee;
    }

    @Override
    public Integer deliveryStatistics(LocalDate begin, LocalDate end,String courierid) {
        LocalDateTime totalbegin = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime totalend = LocalDateTime.of(end, LocalTime.MAX);
        Integer totalstatus=Orders.COMPLETED;
        Map map=new HashMap();
        map.put("totalbegin",totalbegin);
        map.put("totalend",totalend);
        map.put("totalstatus",totalstatus);
        map.put("courierid",courierid);
        Integer totalorder= orderMapper.gettotalorder(map);
        return totalorder;
    }

    @Override
    public Double distanceStatistics(LocalDate begin, LocalDate end, String courierid) {
        LocalDateTime totalbegin = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime totalend = LocalDateTime.of(end, LocalTime.MAX);
        Integer totalstatus=Orders.COMPLETED;
        Map map=new HashMap();
        map.put("totalbegin",totalbegin);
        map.put("totalend",totalend);
        map.put("totalstatus",totalstatus);
        map.put("courierid",courierid);
        Double totaldistance= orderMapper.totaldistance(map);
        return totaldistance;
    }
}

